package events


import (
	"github.com/jinzhu/gorm"
	"meman/sys/basic"
)

const (
	TABLE_SUBSCRIPTIONS = "subscriptions"
	TABLE_SUB_PARAMS = "subscription_params"

	//sql 常量化
	SELECT_RESULT_SQL = "subscriptions.*, subscribers.subscriber_name, subscribers.subscriber_key, message_classes.class_name, message_classes.class_key"
	JOIN_SUBSCRIPTIONS_And_SUBSCRIBERS = "JOIN subscribers ON subscribers.subscriber_id = subscriptions.subscriber_id"
	JOIN_SUBSCRIPTIONS_And_MSGCLASSES = "JOIN message_classes ON message_classes.class_id = subscriptions.message_class_id"
)



/**
subscription表
 */
type Subscription struct {
	SubscriptionId int `gorm:"primary_key;AUTO_INCREMENT;column:subscription_id"`
	SubscriberId int `gorm:"column:subscriber_id"`
	MessageClassId int `gorm:"column:message_class_id"`
	ReceptionChannel string  `gorm:"column:reception_channel"`
	Status int `gorm:"column:status"`
	SubscribeTime int64 `gorm:"column:subscribe_time"`
	Timeout int `gorm:"column:timeout"`
}

/**
这个是subcription left join 消息表和订阅者表返回数据的一个struct
 */
type SubscriptionResult struct {
	SubscriptionId int `gorm:"primary_key;AUTO_INCREMENT;column:subscription_id"`
	SubscriberId int `gorm:"column:subscriber_id"`
	MessageClassId int `gorm:"column:message_class_id"`
	ReceptionChannel string  `gorm:"column:reception_channel"`
	Status int `gorm:"column:status"`
	SubscribeTime int64 `gorm:"column:subscribe_time"`
	Timeout int `gorm:"column:timeout"`

	SubscriberName string `gorm:"column:subscriber_name"`
	SubscriberKey string `gorm:"column:subscriber_key"`

	ClassKey string `gorm:"column:class_key"`
	ClassName string `gorm:"column:class_name"`

}

/**
subscription param 参数表
 */
type SubscriptionParams struct {
	ParamId int `gorm:"primary_key;AUTO_INCREMENT;column:param_id"`
	SubscriptionId int `gorm:"column:subscription_id"`
	ParamName string `gorm:"column:param_name;type:char(100)"`
	ParamValue string  `gorm:"column:param_value"`
}




/**
获取订阅列表
@param conds map[string]interface{} where语句参数
@param page int  当前页码
@param pageSize int  每页有几个数据
@return []Message,count  返回消息数组,和一共有多少条数据
 */
func (s *Subscription) GetSubscriptionList(db *gorm.DB,conds map[string]interface{}, page, perPageNums int) ([]SubscriptionResult, error){
	start := GetPageStart(page, perPageNums)

	var subscriptionResults []SubscriptionResult
	err := db.Table(TABLE_SUBSCRIPTIONS).Select(SELECT_RESULT_SQL).Joins(JOIN_SUBSCRIPTIONS_And_SUBSCRIBERS).Joins(JOIN_SUBSCRIPTIONS_And_MSGCLASSES).Where(conds).Order("subscription_id desc").Limit(perPageNums).Offset(start).Find(&subscriptionResults).Error
	return subscriptionResults, err
}

func (s *Subscription) Count(conds map[string]interface{}) (*gorm.DB, int64){
	var count int64
	db := basic.Read()
	db.Table(TABLE_SUBSCRIPTIONS).Joins(JOIN_SUBSCRIPTIONS_And_SUBSCRIBERS).Joins(JOIN_SUBSCRIPTIONS_And_MSGCLASSES).Where(conds).Count(&count)
	return db, count
}

/**
获取指定ID的错误日志.
@param id int 日志logId
@return
 */
func (s *Subscription) GetSubscriptionDetail(id int) ([]SubscriptionResult, error){
	db := basic.Read()
	var subscriptionResults []SubscriptionResult
	err := db.Table(TABLE_SUBSCRIPTIONS).Select(SELECT_RESULT_SQL).Joins(JOIN_SUBSCRIPTIONS_And_SUBSCRIBERS).Joins(JOIN_SUBSCRIPTIONS_And_MSGCLASSES).Where("subscription_id = ?", id).Find(&subscriptionResults).Error
	return subscriptionResults, err
}


/**
插入一条数据
 */
func(s *Subscription) Insert() error {
	db := basic.Write()
	err := db.Table(TABLE_SUBSCRIPTIONS).Save(&s).Error
	return err
}

/**
根据id查找数据
 */
func(s *Subscription) GetSubscriptionParams(id int) (map[string]interface{}, error) {
	db := basic.Read()
	var subscriptionParams []SubscriptionParams
	err := db.Table(TABLE_SUB_PARAMS).Where("subscription_id = ?", id).Find(&subscriptionParams).Error

	conds := make(map[string]interface{})
	for _, sub := range subscriptionParams  {
		conds[sub.ParamName] = sub.ParamValue
	}

	return conds, err
}

/**
更新
 */
func(s *Subscription) Update(id int) error {
	db := basic.Write()
	err := db.Table(TABLE_SUBSCRIPTIONS).Where("subscription_id = ?", id).Updates(s).Error
	return err
}

/**
删除, 根据id 删除数据
 */
func(s *Subscription) DeleteById(id int) error {
	db := basic.Write()
	err := db.Table(TABLE_SUBSCRIPTIONS).Where("subscription_id = ?", id).Delete(&s).Error
	return err
}


/**
保存subscription 的各项参数
 */
func (s *Subscription) SaveSubscriptionParams(id int, subParams map[string]string ) error {


	var subscriptionParams []SubscriptionParams
	for k,v := range subParams  {
		subscriptionParam := SubscriptionParams{
			SubscriptionId:id,
			ParamName:k,
			ParamValue:v,
		}
		subscriptionParams = append(subscriptionParams, subscriptionParam)
	}

	db := basic.Write()

	tx := db.Begin()
	//删除原有参数
	err := tx.Table(TABLE_SUB_PARAMS).Where("subscription_id=?", id).Delete(SubscriptionParams{}).Error
	if err != nil {
		tx.Rollback()
		return err
	}
	//设置新参数
	for _, subParams := range subscriptionParams {
		err = tx.Table(TABLE_SUB_PARAMS).Save(&subParams).Error
		if err != nil {
			tx.Rollback()
			return err
		}
	}

	tx.Commit()

	return nil
}

func (s *Subscription) ClearSubscriptionParams(id int) error  {
	db := basic.Write()
	err := db.Table(TABLE_SUB_PARAMS).Where("subscription_id = ?", id).Delete(SubscriptionParams{}).Error
	return err
}
